package com.example.educationalsystem.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.educationalsystem.common.util.ExcelListener;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.entity.Classroom;
import com.example.educationalsystem.entity.ClassroomApplication;
import com.example.educationalsystem.entity.Course;
import com.example.educationalsystem.entity.Student;
import com.example.educationalsystem.entity.Vo.CourseVo;
import com.example.educationalsystem.service.IClassroomApplicationService;
import com.example.educationalsystem.service.IClassroomService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static ch.qos.logback.core.joran.action.ActionConst.NULL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zpc
 * @since 2022-12-21
 */
@RestController
@RequestMapping("/classroomApplication")
@Api(value = "/classroomApplication",tags = "教室占用信息管理")
public class ClassroomApplicationController {
    @Autowired
    private IClassroomApplicationService iClassroomApplicationService;

    @ApiOperation(value = "导出教室信息",notes = "导出教室信息")
    @ResponseBody
    @GetMapping("Download")
    public void myDownload(HttpServletResponse response, @RequestParam String tableName) throws IOException {

        try{
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename="+ new String(tableName.getBytes(StandardCharsets.UTF_8),"ISO8859-1")+".xls");
            EasyExcel.write(response.getOutputStream(), ClassroomApplication.class).sheet(tableName).doWrite(iClassroomApplicationService.getBaseMapper().selectList(Wrappers.lambdaQuery()));
        }catch(Exception e)
        {
            response.reset();
        }


    }
    @ApiOperation(value = "导入教室信息",notes = "导入教室信息")
    @ResponseBody
    @PostMapping("Import")
    public ResponseJson myImport(MultipartFile file) {
        ResponseJson responseJson=new ResponseJson();
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, ClassroomApplication.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            System.out.println(list.size());
            if (list.size() >= 1) {
                for (int i = 0; i < list.size(); i++) {
                    ClassroomApplication classroomApplication = (ClassroomApplication) list.get(i);
//                    System.out.println(Classroom.toString());

                    //使用mybatis-plus添加到数据库
                    Boolean res=iClassroomApplicationService.save(classroomApplication);
                    if(res)
                    {
                        responseJson.setStatus(200);
                        responseJson.setMsg("导入成功！");
                    }
                    else {
                        responseJson.setStatus(400);
                        responseJson.setMsg("导入失败！");
                    }
                    System.out.println(res);
                }
            }

        } catch (Exception e) {
            responseJson.setStatus(400);
            responseJson.setMsg(e.toString());
            e.printStackTrace();
        }

        return responseJson;
    }
    @ApiOperation(value = "批量删除教室信息",notes = "根据教室编号，删除多条教室信息")
    @DeleteMapping("/deleteClassroomApplications")
    @ResponseBody
    public  ResponseJson deleteClassroomApplications( @ApiParam(name = "classroomApplicationIds", value = "教室占用IDs", required = true) @RequestParam String classroomApplicationIds)
    {
        ResponseJson responseJson=new ResponseJson();
        String[] idArr =classroomApplicationIds.split(",");
        List<String> idList = Arrays.asList(idArr);
        boolean result=iClassroomApplicationService.removeByIds(idList);
        System.out.println(result);
        if(result)
        {
//            responseJson.setData(courseOne);
            responseJson.setMsg("批量删除成功！");
            responseJson.setStatus(200);
        }
        else
        {
            responseJson.setMsg("批量删除失败");
            responseJson.setStatus(400);
        }
        return responseJson;

    }
    @ApiOperation(value = "分页查询教室占用信息", notes = "分页查询教室占用信息，需要提供页数和一页大小（即一页几条数据）")
    @GetMapping(value = "/classroomApplicationPage")
    @ResponseBody
    public ResponseJson userpage(@RequestParam long current, @RequestParam long size) {
        ResponseJson responseJson = new ResponseJson();
        Page<ClassroomApplication> classroomApplicationPage = new Page<>(current, size);
        Page<ClassroomApplication> classroomApplicationPages = iClassroomApplicationService.getBaseMapper().selectPage(classroomApplicationPage, null);
        responseJson.setMsg("分页查询成功");
        responseJson.setData(classroomApplicationPages);
        responseJson.setStatus(200);
        return responseJson;
    }
    @GetMapping("/getAllClassroomApplication")
    @ApiOperation(value = "获取所有教室占用信息",notes = "获取所有教室占用信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getAllClassroomApplication()
    {
        ResponseJson responseJson=new ResponseJson();
        List<ClassroomApplication> classroomlist=iClassroomApplicationService.getBaseMapper().selectList(Wrappers.lambdaQuery());
        if(classroomlist!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(classroomlist);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，无教室信息！");
        }
        return responseJson;
    }

    @ApiOperation(value = "增加教室占用信息",notes = "增加一条教室占用信息记录")
    @PostMapping("/insertClassroomApplication")
    @ResponseBody
    public ResponseJson insertClassroomApplication(@RequestBody ClassroomApplication requestClassroomApplication)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<ClassroomApplication> queryWrapper=new QueryWrapper<>();
        System.out.println(requestClassroomApplication.getClassroomId());
        ClassroomApplication classroomOne=iClassroomApplicationService.getBaseMapper().selectOne(queryWrapper.eq("classroom_application_id",requestClassroomApplication.getClassroomApplicationId()));
        if(classroomOne==null)
        {
            Boolean result=iClassroomApplicationService.save(requestClassroomApplication);
            if(result)
            {
                responseJson.setMsg("增加成功！");
                responseJson.setStatus(200);
                responseJson.setData(requestClassroomApplication);

            }
            else
            {
                responseJson.setStatus(400);
                responseJson.setMsg("增加失败！");
            }
        }
        else
        {
            responseJson.setStatus(400);
            responseJson.setMsg("该记录已存在！");
        }
        return responseJson;
    }


    @ApiOperation(value = "删除教室占用信息",notes = "根据教室占用ID，删除一条教室占用信息")
    @DeleteMapping("/deleteClassroomApplication")
    @ResponseBody
    public  ResponseJson deleteClassroomApplication( @ApiParam(name = "classroomApplicationId", value = "教室占用ID", required = true) @RequestParam String classroomApplicationId)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<ClassroomApplication> queryWrapper=new QueryWrapper<>();
        ClassroomApplication classroomApplicationOne=iClassroomApplicationService.getBaseMapper().selectOne(queryWrapper.eq("classroom_application_id",classroomApplicationId));
        if(classroomApplicationOne!=null)
        {
            int result=iClassroomApplicationService.getBaseMapper().deleteById(classroomApplicationOne.getClassroomApplicationId());
            System.out.println(result);
            if(result==1)
            {
                responseJson.setData(classroomApplicationOne);
                responseJson.setMsg("删除成功！");
                responseJson.setStatus(200);
            }
            else
            {
                responseJson.setMsg("删除失败");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("教室信息不存在！");
        }
        return responseJson;

    }

    @ApiOperation(value = "更新教室占用信息",notes = "更新教室占用信息，必须填写教室占用ID")
    @PutMapping("/updateClassroomApplication")
    @ResponseBody
    public ResponseJson updateClassroomApplication(@RequestBody  ClassroomApplication resquestClassroomApplication)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<ClassroomApplication> queryWrapper=new QueryWrapper<>();
        ClassroomApplication classroomApplicationOne=iClassroomApplicationService.getBaseMapper().selectOne(queryWrapper.eq("classroom_application_id",resquestClassroomApplication.getClassroomApplicationId()));
        if(classroomApplicationOne!=null)
        {
            QueryWrapper<ClassroomApplication> queryWrapper1=new QueryWrapper<>();
            int result=iClassroomApplicationService.getBaseMapper().update(resquestClassroomApplication,queryWrapper1.eq("classroom_application_id",resquestClassroomApplication.getClassroomApplicationId()));
            if(result==1)
            {
                responseJson.setMsg("更新成功！");
                responseJson.setStatus(200);
                responseJson.setData(iClassroomApplicationService.getBaseMapper().selectOne(queryWrapper.eq("classroom_application_id",resquestClassroomApplication.getClassroomApplicationId())));
            }
            else {
                responseJson.setMsg("更新失败！");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setMsg("教室信息不存在");
            responseJson.setStatus(404);
        }
        return responseJson;
    }
}

